import pymysql


class DButils:
    def __init__(self, host, database, user, password, port=3306, charset='utf8'):
        self.host = host
        self.port = port
        self.database = database
        self.user = user
        self.password = password
        self.charset = charset

    def select(self, sql, data=None):
        db = pymysql.connect(
            host=self.host,
            port=self.port,
            database=self.database,
            user=self.user,
            password=self.password,
            charset=self.charset
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql, data)
                result = cursor.fetchall()
                return result
        except Exception as e:
            print('数据库操作失败!', e)
        finally:
            db.close()

    def update(self, sql, data=None):
        db = pymysql.connect(
            host=self.host,
            port=self.port,
            database=self.database,
            user=self.user,
            password=self.password,
            charset=self.charset
        )

        try:
            with db.cursor() as cursor:
                cursor.execute(sql, data)
                db.commit()
        except Exception as e:
            print('数据库操作失败!', e)
        finally:
            db.close()


if __name__ == '__main__':
    o_sql = DButils('localhost', 'dbase', 'root', 'root')
    # o_sql.update(sql, data)
    # sql = ("create table person("
    #        "username varchar(20),"
    #        "age int,"
    #        "sex char(4),"
    #        "high double(3,2)"
    #        ")")
    # o_sql.update(sql)
    n = int(input('请输入要添加的人数:'))
    for i in range(n):
        sql = "insert into person values(%s,%s,%s,%s)"
        data = (input('请输入姓名:'), input('请输入年龄:'), input('请输入性别:'), input('请输入身高:'))
        o_sql.update(sql, data)